$(window).ready(function(){
    var slideShow_CaId="f410570a553646e5bbf1bf305f558643",
        hotPro_Icon_Id="68834ed22b6a4c7ba87be2f4fcc0ef8f",
        hotPro_CategoryId_from_Content="d032f821f89e43cba8962a6d569f584d";
        let scriptImgBp = {
            "水果":"-271px -42px",
            "蔬菜":"-271px -388px",
            "粮油米面":"-271px -157px",
            "畜牧水产":"-271px -100px",
            "农副加工":"-271px -216px",
            "苗木花草":"-271px -271px",
            "农资农机":"-271px -332px",
            "种子种苗":"-271px -42px"
        };


        $.ajax({
            url:"/index/getMenu",
            type:'get',
            async:false,
            success:function(data){
                    var da=data.data;
                    // 导航栏Collections的下拉导航
                    var collectionNav_li="";
                    //搜索框左边的分类
                    var collectionOpt="";
                    for(var d in da){
                        collectionNav_li+="<li> <a href=\"/collection.html?keyword=&categoryId="+da[d].id+"\" class=\"site-nav__link\">"+da[d].name+"</a> </li>";
                        collectionOpt+='<option value="'+da[d].id+'">'+da[d].name+'</option>';
                    }
                    $("#collectionNav").append(collectionNav_li);
                    $("#collection-option").append(collectionOpt);

                    // 正中央左边的导航
                    if(da!=null)
                    {
                        let txt='';
                        for(var d in da) {
                                txt += `<li class="sdc-element vetical-menu1 site-nav--has-dropdown" aria-haspopup="true">
                							<a href="/agriecomIndex/search/forward?keyword=&categoryId=`+da[d].id+`" class="site-nav__link">
                								<div class="element-main">
                									<div class="collection-icon" id="coll-icon">
                									<!--<img src="/images/book.png" alt="collection icon">-->
                									</div>
                									<div class="collection-area have-icons" >
                										<div class="collection-name" id="categoryName">
                											 `+da[d].name+`
                										</div>
                									</div>
                								</div>
                								<span class="icon icon-arrow-right" aria-hidden="true"></span>
                							</a>
                							<ul class="site-nav__dropdown vetical__dropdown vetical__dropdown1">
                								<li class="nav-links nav-links01 grid__item large--one-half">
                									<ul id="`+da[d].name+`">
                									</ul>
                								</li>
                								<li class="grid__item large--one-half">
                									<ul>
                										<li class="list-title">新产品</li>
                										<li class="list-product">
                										<div class="list-product-image">
                											<a href="product.html"><img src="/images/crop.jpg" alt="Example Book"></a>
                										</div>
                										<!--<div class="list-product-name">-->
                											<!--Example Book-->
                										<!--</div>-->
                										<div class="list-product-link">
                											<a href="product.html">更多</a>
                										</div>
                										</li>
                									</ul>
                								</li>
                							</ul>
                						</li>`;
                        }
                        //先把整体的导航栏代码写入，后面再修改要显示的数据
                        $("ul.sdcollections-list").append(txt);
                        //添加左导航栏小图标
                        $('ul.sdcollections-list div#coll-icon').each(function(index,ele){
                            for(let[key,value] of Object.entries(scriptImgBp)){
                                if(key === $(ele).siblings('div.collection-area').children('div').text().trim()){
                                     $(ele).css({"background-position":value});
                                }
                            }

                        });
                        //再子分类的数据插入
                        for(var d in da){
                            var child=da[d].children;
                            let  lis='';
                            for(var t in child)
                            {
                                lis+=`<li class="list-unstyled nav-sub-mega">
                                <a href="/agriecomIndex/search/secondForward?categoryId=`+child[t].id+`">`+child[t].name+`</a>
                                <ul class="list_con">`;
                                //再把子类的子类添加进去
                                var grandson=child[t].children;
                                for(var x in grandson){
                                    lis+=`  <li>
                                                 <a href="/agriecomIndex/search/paramForward?categoryId=`+grandson[x].id+`">`+grandson[x].name+`</a>
                                             </li>`;
                                }
                                lis+=`</ul></li>`;
                            }
                            $("ul#"+da[d].name).append(lis);
                         }

                    }
            }

        });

        //内容分类中首页下轮播图的categoryId
        $.get("/index/getContentsBycategoryId?categoryId="+slideShow_CaId, function (data, status) {
            //导航栏下面正中央的轮播图
            var li_BigPic=$("div#slider ul").children();
            var li_SmaPic=  $("div#carousel ul").children();
            //前端写死6张轮播图，
                $(li_BigPic[0]).find('img').css({"width":885,"height": 476.533});
            for(var i=0;i<6;i++){
                $(li_BigPic[i]).find('img').attr('src',data[i].pic);
                $(li_SmaPic[i]).find('img').attr('src',data[i].pic);
                $(li_SmaPic[i]).find('a').text(data[i].content);
                $(li_SmaPic[i]).find('a').attr("href",data[i].url);//这里需要在数据库中添加连接和传参
                $(li_SmaPic[i]).find('a').attr("onclick","location.href = '"+data[i].url+"'")

                var date = new Date(data[i].updateDate);
                var updateDate=date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                $(li_SmaPic[i]).find('span.cr-desc').text(updateDate);
            }




    });


        //前端显示7条
        $.get("/index/getProudceShow?page=1&rows=7&order=update_date desc", function (data, status) {
            data=data.data;
            //最新供应
            //后面整理，在去掉newInsert.js后，这里可以去掉
            //  $("ul.new-apply-top-ListMain-content").empty();
             var options="";
             for(var d in data){
                 var date = new Date(data[d].updateDate);
                var updateDate=date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                 options+=`<li>
									<a href="product.html?id=`+data[d].produceId+`" target="_blank">
                                        <span style='width:90px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: rgb(102, 102, 102);font-size: 16px;' class="apply_time">`+updateDate+`</span>
                                        <span style='width:190px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: rgb(102, 102, 102);font-size: 16px;' class="apply_category">`+data[d].produceName+` </span>
                                        <span style='width:90px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: rgb(102, 102, 102);font-size: 16px;' class="apply_money">`+data[d].price+``+data[d].unit+`</span>
									</a>
								</li>`;
             }
            $("ul.new-apply-top-ListMain-content").append(options);


        })


    //-------------------------------------------------------
    //热门产品
    let newProLineAndContent = '<div class="productLine">'+
                                    '<div style="position: relative;">'+
                                        '<div class="productList-triangle"></div>'+
                                    '</div>'+
							    '</div>'+
						        '<div class="productList-content">'+
                                    '<div class="productList-contentMain">'+
                                        '<div class="productList-contentHot">'+
                                            '<ul class="contentHot-List">'+
                                            '</ul>'+
                                        '</div>'+
                                    '</div>'+
							    '</div>';
    let [trendApplyDiv] = [(ele)=>{ $(ele).after(newProLineAndContent);}];

    var categoryNode;
    $.ajax({//从内容管理上拿，返回list             parentId为热门产品id
        url: '/index/getNodes?ParentId='+hotPro_CategoryId_from_Content,
        type: 'get',
        async:false,
        success: function (data) {
            //得到热门产品分类下的所有结点（水果蔬菜等）
            categoryNode=data.data;
        }
    });
    let newListContentHotChildren = new Array(categoryNode.length);//这里的10只是大概
    for(var d=0 ;d< newListContentHotChildren.length;d++)
        newListContentHotChildren[d]='';
    $.ajax({
        url: '/index/getHotProducts?page=0&limit=100',
        type: 'get',
        async:false,
        // where:{page:0,limit:100},//这里的100是指全部
        success: function (da) {
            //将产品分类别
            for(var t in da) {
                //每个产品都去找到第一级的分类名称
                $.ajax({
                    url: '/index/getAncestorNode',
                    type: 'get',
                    async: false,
                    data: {categoryId: da[t].categoryId, level:"1"},
                    success: function (data) {

                        for (var d in categoryNode) {
                            if(data.name=="蔬菜"||data.name=="水果")data.name="水果蔬菜";
                            if (data.name == categoryNode[d].name) {
                                newListContentHotChildren[d] += '<li class="one-third contentHot-ListChildren">' +
                                    '<div class="top">'
                                    + da[t].produceName + '<img src="/assets/images/hot.png">'
                                    + '</div>' +
                                    '<div class="middle">' + da[t].ProduceBrief + '</div>' +
                                    '<div class="bottom">' +
                                    '<button class="button button--winona button--border-thin button--round-s" data-text="直接购买">' +
                                    '<span data-id='+da[t].produceId+'>直接购买</span>' +
                                    '</button>' +
                                    '</div>' +
                                    '</li>';
                                break;
                            }
                        }

                    }
                })
            }
            //
            // for(var d in data) {
            //     newListContentHotChildren += '<li class="one-third contentHot-ListChildren">'+
            //         '<div class="top">'
            //         + data[d].produceName + '<img src="/assets/images/hot.png">'
            //         +'</div>'+
            //         '<div class="middle">' + data[d].ProduceBrief + '</div>'+
            //         '<div class="bottom">'+
            //         '<button class="button button--winona button--border-thin button--round-s" data-text="直接购买">'+
            //         '<span>直接购买</span>'+
            //         '</button>'+
            //         '</div>'+
            //         '</li>' ;
            // }

        }
    })
    function loadHotProduct(ele) {
        var name=$(ele).find("div").text();
        for(var d=0;d<categoryNode.length;d++)
            if(categoryNode[d].name==name)
            {
                if(newListContentHotChildren[d]!=undefined)
                    $("ul.contentHot-List").append(newListContentHotChildren[d]);

                break;
            }
            $('.bottom button').each((index,ele)=>{
                $(ele).off('click');
                $(ele).on('click',()=>{
                    window.location.href = "product.html?id="+$(ele).children("span").attr('data-id')
                });
            });
    }
    //热门产品
    //水果、蔬菜因为并为一个分类，动态获取较复杂，所以在前面先创建一个水果蔬菜分类
    var category_firstList=``;
    var category_secondList=``;
    for(var d in categoryNode){
        if(categoryNode[d].name=="水果"){
            category_firstList += `<li class="one-third big_icon" style="margin: 0;">
                            						
                            							<img src="" alt="" width="119" height="129" id="水果蔬菜T">
                            							<div class="first_text">水果蔬菜</div>
                            						
                            					</li>`;
            continue;
        }
        // 这里循环三次上面的
        if(d<3) {
            category_firstList +=`<li class="one-third big_icon" style="margin: 0;">
                            						
                            							<img src="" alt=""  width="119" height="129" id="` + categoryNode[d].name + `T">
                            							<div style="margin-left:20px;">` + categoryNode[d].name + `</div>
                            						
                            					</li>`;
        } else {//这里再循环下面三次的
            category_secondList +=`<li class="one-third big_icon" style="margin: 0;">
                            						
                            							<img src="" alt="" width="119" height="129" id="` + categoryNode[d].name + `T">
                            							<div style="margin-left:20px;">` + categoryNode[d].name + `</div>
                            						
                            					</li>`;
        }
    }
    $(".productListContent_firstList").append(category_firstList);
    $(".productListContent_secondList").append(category_secondList);
    //添加热销商品图标
    $.ajax({
        url:"/index/getContentsBycategoryId?&categoryId="+hotPro_Icon_Id,
        async:false,
        type:'get',
        success:function(data){
            for(var d in data)
                if(data[0]!=null)
                    $("img#" + data[d].title + "T").attr("src", data[d].pic);
        }
    });



    trendApplyDiv('.productListContent_first');

    loadHotProduct( $("li.one-third.big_icon").eq(0))

    $('.bottom button').each((index,ele)=>{
        $(ele).on('click',()=>{
             window.location.href = "product.html?id="+$(ele).children("span").attr('data-id')
         });
     });

    /*三角形移动*/
    let [LeftDistance,clickLeftDistance,tempLeft]= [$('.first_text').width()/2,null,null];
    $('.productList-triangle').css({'left':LeftDistance.left});
    //下面的.productListContent_firstList要写成参数的形式
    let productListCon_effect = (active_dom)=>{
        let ArrayProductList = $(active_dom).find('li.big_icon');
        $(active_dom).find('li.big_icon').each((index,ele)=>{
            $(ele).on('click',()=>{
                //每次点击就清空数据
                // newListContentHotChildren='';
                //这里要写的是动态添加框跟三角形 这里有缺陷就是只能是两行 如果是三行要用循环遍历出来即可
                (index < Math.ceil(ArrayProductList.length/2))?((()=>{
                    clickLeftDistance = $(ele).position();
                    tempLeft = $('.productList-triangle').position().left;
                    $('.productListContent').find("div.productLine").remove();
                    $('.productListContent').find('div.productList-content').remove();
                    trendApplyDiv('.productListContent_first');
                    loadHotProduct(ele);
                    $('.productList-triangle').css({'left':tempLeft});
                    $('.productList-triangle').stop(true,true).animate({
                        'left':clickLeftDistance.left+LeftDistance+180.5
                    },500);
                    // $('.productList-triangle').css({'left':clickLeftDistance.left});
                })()):((()=>{
                    clickLeftDistance = $(ele).position();
                    tempLeft = $('.productList-triangle').position().left;

                    $('.productListContent').find("div.productLine").remove()
                    $('.productListContent').find('div.productList-content').remove();
                    trendApplyDiv('.productListContent_second');
                    loadHotProduct(ele);
                    $('.productList-triangle').css({'left':tempLeft});
                    $('.productList-triangle').stop(true,true).animate({
                        'left':clickLeftDistance.left-LeftDistance-180.5
                    },500);
                })());
                /*下面框淡入淡出*/
                $('.contentHot-List').children('li').remove();
                // circulateFn(6,'.contentHot-List',newListContentHotChildren);//为了增加数据
                //---------------------------
                // $("ul.contentHot-List").append(newListContentHotChildren);
                loadHotProduct(ele);
                $('.contentHot-List').each((index,ele)=>{
                    $(ele).fadeOut(100).fadeIn(500);
                });
            });

        });
    };

    productListCon_effect('.productListContent');
//----------------------------------------------------------------------------
//
// });
//
//
// $(document).ready(function() {
    /* 商品推荐模块 */

    //spotlight商品模块
    $.ajax({
        url: "/recommend?columnId=1&userId=1",
        dataType: "json",
        type: "GET",
        success : function(data){
            var title_p=$(".product-title");
            var price_p=$(".product-price");
            var a=$(".grid__image a");
            console.log(a)
            $.each(data,function (i, ele) {
                var prodoctURL="product.html?id="+ele.produceId;
                $(title_p[i]).html("<a href="+prodoctURL+">"+ele.produceName+"</a>");
                console.log(ele.produceName)
                var price_span=$(price_p[i]).children("span");
                $(price_span[0]).html("$"+ele.price);
                // "$"+ele.price+20
                var oldPrice=ele.price+20;
                $($(price_p).children("s")[i].children[0]).html("$"+oldPrice);
                var img=a[i].children[0];
                img.setAttribute("src",ele.produceImg.split(",")[0]);
                a[i].setAttribute("href","/product.html?id="+ele.produceId);
            })
        }
    });

    //广告
    $.ajax({
        url: "/agriecomIndex/proRecommend/advertise",
        dataType: "json",
        type: "GET",
        success : function(data){
            $(".banner-area a").attr("href",data[0].url);
            $(".banner-area a img").attr("src",data[0].pic);
        }
    });

    /* 新闻资讯模块 */
    //热门新闻
    $.ajax({
        url: "/agriecomIndex/newsInfo/hotNews?page=1&limit=3",
        dataType: "json",
        type: "GET",
        success : function(data){
            $(".top_news").attr("href","/agriecomPage/news/forward?newsId="+data[0].id)         //topNews_a 链接
            $(".top_news img").attr("src",data[0].pic);
            $(".top_news img").attr("alt","图片加载失败");
            $(".top_news span").html(data[0].title);

            var a=$(".left_news");//两个left_news a
            $(a[0]).attr("href","/agriecomPage/news/forward?newsId="+data[1].id);          //链接
            $($(a[0]).children("img")[0]).attr("src",data[1].pic);
            $($(a[0]).children("img")[0]).attr("alt","图片加载失败");
            $($(a[0]).children("span")[0]).html(data[1].title);

            $(a[1]).attr("href","/agriecomPage/news/forward?newsId="+data[2].id);          //链接
            $($(a[1]).children("img")[0]).attr("src",data[2].pic);
            $($(a[1]).children("img")[0]).attr("alt","图片加载失败");
            $($(a[1]).children("span")[0]).html(data[2].title);

        }
    });
    //成功案例
    $.ajax({
        url: "/agriecomIndex/newsInfo/successExample?page=1&limit=4",
        dataType: "json",
        type: "GET",
        success: function (data) {
            $(".content_first a").attr("href","/agriecomPage/news/forward?newsId="+data[0].id);            //链接
            $(".content_first a img").attr("src",data[0].pic);
            $(".content_first a span").html(data[0].title);

            $(".content_second a").attr("href","/agriecomPage/news/forward?newsId="+data[1].id);            //链接
            $(".content_second a img").attr("src",data[1].pic);
            $(".content_second a span").html(data[1].title);

            $(".content_third a").attr("href","/agriecomPage/news/forward?newsId="+data[2].id);            //链接
            $(".content_third a img").attr("src",data[2].pic);
            $(".content_third a span").html(data[2].title);

            $(".content_forth a").attr("href","/agriecomPage/news/forward?newsId="+data[3].id);            //链接
            $(".content_forth a img").attr("src",data[3].pic);
            $(".content_forth a span").html(data[3].title);

            //更多新闻
            $(".success-news-title p")[1].children[0].setAttribute("href","/news.html");      //链接
        }
    });

    /* 热议资讯 */
    $.ajax({
        url: "/agriecomIndex/newsInfo/discussion?page=1&limit=4",
        dataType: "json",
        type: "GET",
        success: function (data) {
            var lis=$(".bussiness-news-con_list li");
            $.each(data,function (i,ele) {
                $(lis[i].children[0]).html("<a href='"+"/agriecomPage/news/forward?newsId="+ele.id+"'>"+ele.title+"</a>");        //热议资讯链接
            })
            $(".bussiness-news-title p")[1].children[0].setAttribute("href","/news.html");        //更多热议资讯 链接
        }
    });
    /* 最新资讯 */
    $.ajax({
        url: "/agriecomIndex/newsInfo/latestNews?page=1&limit=4",
        dataType: "json",
        type: "GET",
        success: function (data) {

            var lis=$(".school-news-con_list li");
            $.each(data,function (i,ele) {
                $(lis[i].children[0]).html("<a href='"+"/agriecomPage/news/forward?newsId="+ele.id+"'>"+ele.title+"</a>");        //最新资讯链接
            })
            $(".school-news-title p")[1].children[0].setAttribute("href","/news.html");        //更多最新资讯 链接
        }
    });
    /* 最新行情 */
    $.ajax({
        url:"/agriecomIndex/LatestInfo/latestQuotation?page=1&limit=10",
        dataType:"json",
        type:"GET",
        success:function (data) {
            var ul=$(".new-info-contentMainList");
            ul.html("");                                //清空并循环追加
            $.each(data,function (i, ele) {
                var proName;
                var proCategoryName;
                var price;
                var unit;
                $.ajax({                            //获取产品名和产品分类名
                    url:"/agriecomIndex/LatestInfo/proAndCategoryName?id="+ele.produceId,
                    dataType:"json",
                    type:"GET",
                    success:function (data) {
                        proName=data.data.productName;
                        proCategoryName=data.data.categoryName;
                        price=data.data.price;
                        unit=data.data.unit;
                        var date =new Date(ele.recordTime);
                        ul.append("<li><a href=\"javascript:;\" target=\"_blank\"><span style='width:60px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;' class=\"type\">"+ele.name+"</span><span style='width:60px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;' class=\"product_name\">"+proName+"</span><span style='width:65px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;' class=\"classify_name\">"+proCategoryName+"</span><span style='width:64px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;' class=\"info_time\">"+ (date.getMonth() + 1) +"-" + date.getDate()+"</span><span style='width:64px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;' class=\"info_prie\">"+price+unit+"</span><span style='width:64px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;' class=\"info_upDown\">"+ele.trend+"</span></a></li>");
                        //date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
                    }
                })
            })

        }
    })


    //最新资讯
    $.ajax({
        url:"/agriecom/news/mostLatestNews?page=1&limit=7",
        dataType:"json",
        type:"GET",
        success:function(data){
            $(".new-purchase-top-ListMain-content").html("");
            $.each(data,function(i,ele){
                $(".new-purchase-top-ListMain-content").append("<li style='width:379.52px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;'><a style='color: rgb(102, 102, 102);font-size: 16px;' href='/agriecomPage/news/forward?newsId="+ele.id+"'>"+ele.title+"</a></li>");
            })
        }
    })


});

